package cn.cai.pethome.system.controller;

import cn.cai.pethome.base.PreAuthorize;
import cn.cai.pethome.dept.domain.Department;
import cn.cai.pethome.system.service.IMenuService;
import cn.cai.pethome.system.domain.Menu;
import cn.cai.pethome.system.query.MenuQuery;
import cn.cai.pethome.base.util.AjaxResult;
import cn.cai.pethome.base.util.PageList;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    public IMenuService menuService;


    /**
     * 保存和修改公用的
     * @param menu  传递的实体
     * @return Ajaxresult转换结果
     */
    @PreAuthorize(name = "增删菜单",sn = "menu:save",parent_id = 7)
    @PutMapping("/save")
    public AjaxResult addOrUpdate(@RequestBody Menu menu){
        try {
            if( menu.getId()!=null){
                    menuService.update(menu);
            }
            else{
                    menuService.add(menu);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("保存对象失败！" + e.getMessage());
        }

    }
    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value="/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            menuService.deleteById(id);
            return AjaxResult.me();
        } catch (Exception e) {
        e.printStackTrace();
            return AjaxResult.error("删除对象失败！" + e.getMessage());
        }
    }


    /**
     * 批量删除数据
     * @param ids
     * @return
     */
    @PatchMapping
    @ApiOperation(value = "批量删除数据" )
    public AjaxResult menupatch(@RequestBody List<Long> ids){
        try {
            menuService.batchDelete(ids);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return  AjaxResult.error();
        }
    }

    //获取用户
    @GetMapping("/{id}")
    public Menu get(@PathVariable("id")Long id)
    {
        return menuService.findById(id);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @GetMapping("/list")
    public List<Menu> list(){
        return menuService.findAll();
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PreAuthorize(name = "菜单列表",sn = "menu:pagelist",menu_id = 4,parent_id = 7)
    @PostMapping("/pagelist")
    public PageList<Menu> json(@RequestBody MenuQuery query)
    {
        return menuService.queryAll(query);
    }


    @GetMapping
    @ApiOperation(value = "部门树")
    public List<Menu> menuTree(){
        return menuService.getTree();
    }
}
